import { BaseApiService } from './base-api.service'
import { httpClient } from '@/utils/http-client'

/**
 * 权限检查结果接口
 */
export interface PermissionCheckResult {
  permissionName: string
  isGranted: boolean
  fromCache: boolean
  cachedAt?: string
  expiresAt?: string
}

/**
 * 权限缓存统计接口
 */
export interface PermissionCacheStatistics {
  totalCachedPermissions: number
  expiredPermissions: number
  activePermissions: number
  lastUpdated: string
  permissionTypeCount: Record<string, number>
}

/**
 * 用户权限接口
 */
export interface UserPermissions {
  userId: string
  permissions: string[]
  roles: string[]
  organizations: Array<{
    id: string
    name: string
    position: string
  }>
}

/**
 * 权限验证结果接口
 */
export interface PermissionValidationResult {
  isValid: boolean
  errors: Array<{
    field: string
    message: string
  }>
}

/**
 * 权限同步状态接口
 */
export interface PermissionSyncStatus {
  lastSyncTime: string
  syncStatus: 'pending' | 'running' | 'completed' | 'failed'
  errorMessage?: string
  pendingOperations: number
}

/**
 * 权限API服务
 * 处理权限相关的所有API操作
 */
export class PermissionApiService extends BaseApiService {
  constructor() {
    super(httpClient)
  }

  /**
   * 检查当前用户是否有指定权限
   */
  async checkPermission(permissionName: string): Promise<boolean> {
    return this.handleRequest(
      () => this.http.get<boolean>(`/api/permission-cache/is-granted`, { permissionName }),
      { showLoading: false }
    )
  }

  /**
   * 检查指定用户是否有指定权限
   */
  async checkUserPermission(userId: string, permissionName: string): Promise<boolean> {
    return this.handleRequest(
      () => this.http.get<boolean>(`/api/permission-cache/is-granted/${userId}`, { permissionName }),
      { showLoading: false }
    )
  }

  /**
   * 批量检查权限
   */
  async checkPermissions(permissionNames: string[]): Promise<Record<string, boolean>> {
    return this.handleRequest(
      () => this.http.post<Record<string, boolean>>('/api/permission-cache/is-granted-batch', { permissionNames }),
      { showLoading: false }
    )
  }

  /**
   * 批量检查指定用户权限
   */
  async checkUserPermissions(userId: string, permissionNames: string[]): Promise<Record<string, boolean>> {
    return this.handleRequest(
      () => this.http.post<Record<string, boolean>>(`/api/permission-cache/is-granted-batch/${userId}`, { permissionNames }),
      { showLoading: false }
    )
  }

  /**
   * 获取当前用户所有权限
   */
  async getCurrentUserPermissions(): Promise<string[]> {
    return this.handleRequest(
      () => this.http.get<string[]>('/api/permission-cache/all-permissions'),
      { showLoading: false }
    )
  }

  /**
   * 获取指定用户所有权限
   */
  async getUserPermissions(userId: string): Promise<string[]> {
    return this.handleRequest(
      () => this.http.get<string[]>(`/api/permission-cache/all-permissions/${userId}`),
      { showLoading: false }
    )
  }

  /**
   * 获取用户权限详情
   */
  async getUserPermissionDetails(userId?: string): Promise<UserPermissions> {
    const url = userId ? `/api/permissions/user/${userId}` : '/api/permissions/current-user'
    return this.handleRequest(
      () => this.http.get<UserPermissions>(url),
      { showLoading: false }
    )
  }

  /**
   * 刷新权限缓存
   */
  async refreshPermissionCache(userId?: string): Promise<void> {
    const url = userId ? `/api/permission-cache/refresh/${userId}` : '/api/permission-cache/refresh'
    return this.handleRequest(
      () => this.http.post<void>(url),
      {
        showSuccessMessage: true,
        successMessage: '权限缓存已刷新'
      }
    )
  }

  /**
   * 清除用户权限缓存
   */
  async clearUserPermissionCache(userId?: string): Promise<void> {
    const url = userId ? `/api/permission-cache/clear/${userId}` : '/api/permission-cache/clear'
    return this.handleRequest(
      () => this.http.delete<void>(url),
      {
        showSuccessMessage: true,
        successMessage: '权限缓存已清除'
      }
    )
  }

  /**
   * 清除特定权限的缓存
   */
  async clearPermissionCache(permissionName: string, userId?: string): Promise<void> {
    const params: any = { permissionName }
    if (userId) {
      params.userId = userId
    }

    return this.handleRequest(
      () => this.http.delete<void>('/api/permission-cache/clear-permission', { params }),
      {
        showSuccessMessage: true,
        successMessage: '权限缓存已清除'
      }
    )
  }

  /**
   * 预热权限缓存
   */
  async warmupPermissionCache(userIds: string[], permissionNames: string[]): Promise<void> {
    return this.handleRequest(
      () => this.http.post<void>('/api/permission-cache/warmup', { userIds, permissionNames }),
      {
        showLoading: true,
        loadingMessage: '预热权限缓存中...',
        showSuccessMessage: true,
        successMessage: '权限缓存预热完成'
      }
    )
  }

  /**
   * 获取权限缓存统计信息
   */
  async getPermissionCacheStatistics(userId?: string): Promise<PermissionCacheStatistics> {
    const params = userId ? { userId } : {}
    return this.handleRequest(
      () => this.http.get<PermissionCacheStatistics>('/api/permission-cache/statistics', params),
      { showLoading: false }
    )
  }

  /**
   * 验证权限配置
   */
  async validatePermissionConfiguration(): Promise<PermissionValidationResult> {
    return this.handleRequest(
      () => this.http.get<PermissionValidationResult>('/api/permissions/validate'),
      { showLoading: false }
    )
  }

  /**
   * 获取权限同步状态
   */
  async getPermissionSyncStatus(userId?: string): Promise<PermissionSyncStatus> {
    const url = userId ? `/api/permissions/sync-status/${userId}` : '/api/permissions/sync-status'
    return this.handleRequest(
      () => this.http.get<PermissionSyncStatus>(url),
      { showLoading: false }
    )
  }

  /**
   * 手动触发权限同步
   */
  async triggerPermissionSync(userId?: string): Promise<void> {
    const url = userId ? `/api/permissions/sync/${userId}` : '/api/permissions/sync'
    return this.handleRequest(
      () => this.http.post<void>(url),
      {
        showLoading: true,
        loadingMessage: '同步权限中...',
        showSuccessMessage: true,
        successMessage: '权限同步已触发'
      }
    )
  }

  /**
   * 获取权限审计日志
   */
  async getPermissionAuditLogs(params: {
    userId?: string
    startDate?: string
    endDate?: string
    permissionName?: string
    skipCount?: number
    maxResultCount?: number
  } = {}): Promise<{
    items: Array<{
      id: string
      userId: string
      eventType: string
      eventData: string
      ipAddress: string
      userAgent: string
      riskLevel: string
      additionalInfo: string
      eventTime: string
    }>
    totalCount: number
  }> {
    return this.handleRequest(
      () => this.http.get('/api/permissions/audit-logs', params),
      { showLoading: false }
    )
  }

  /**
   * 获取权限使用统计
   */
  async getPermissionUsageStats(params: {
    startDate?: string
    endDate?: string
    groupBy?: 'day' | 'week' | 'month'
  } = {}): Promise<Array<{
    date: string
    permissionName: string
    checkCount: number
    grantedCount: number
    deniedCount: number
  }>> {
    return this.handleRequest(
      () => this.http.get('/api/permissions/usage-stats', params),
      { showLoading: false }
    )
  }

  /**
   * 批量分配权限
   */
  async batchGrantPermissions(params: {
    userIds: string[]
    permissions: string[]
    reason?: string
  }): Promise<{
    successCount: number
    failureCount: number
    results: Array<{
      userId: string
      permissionName: string
      success: boolean
      error?: string
    }>
  }> {
    return this.handleRequest(
      () => this.http.post('/api/permissions/batch-grant', params),
      {
        showLoading: true,
        loadingMessage: '批量分配权限中...',
        showSuccessMessage: true,
        successMessage: '批量权限分配完成'
      }
    )
  }

  /**
   * 批量撤销权限
   */
  async batchRevokePermissions(params: {
    userIds: string[]
    permissions: string[]
    reason?: string
  }): Promise<{
    successCount: number
    failureCount: number
    results: Array<{
      userId: string
      permissionName: string
      success: boolean
      error?: string
    }>
  }> {
    return this.handleRequest(
      () => this.http.post('/api/permissions/batch-revoke', params),
      {
        showLoading: true,
        loadingMessage: '批量撤销权限中...',
        showSuccessMessage: true,
        successMessage: '批量权限撤销完成'
      }
    )
  }

  /**
   * 导出权限配置
   */
  async exportPermissions(params: {
    userIds?: string[]
    roleIds?: string[]
    format?: 'json' | 'excel' | 'csv'
  } = {}): Promise<void> {
    return this.export(
      '/api/permissions/export',
      {
        ...params,
        format: params.format || 'xlsx'
      },
      {
        showLoading: true,
        loadingMessage: '导出权限配置中...',
        filename: `permissions_export_${Date.now()}.${params.format || 'xlsx'}`
      }
    )
  }

  /**
   * 导入权限配置
   */
  async importPermissions(file: File, options: {
    overwriteExisting?: boolean
    validateOnly?: boolean
  } = {}): Promise<{
    successCount: number
    failureCount: number
    errors: Array<{
      line: number
      message: string
    }>
  }> {
    return this.import(
      '/api/permissions/import',
      {
        file,
        ...options
      },
      {
        showLoading: true,
        loadingMessage: '导入权限配置中...',
        showSuccessMessage: true,
        successMessage: '权限配置导入完成'
      }
    )
  }

  /**
   * 获取权限导入模板
   */
  async downloadPermissionTemplate(format: string = 'xlsx'): Promise<void> {
    return this.getImportTemplate(
      '/api/permissions',
      format,
      {
        filename: `permissions_template.${format}`
      }
    )
  }

  /**
   * 验证权限导入数据
   */
  async validatePermissionImport(file: File): Promise<{
    isValid: boolean
    errors: Array<{
      line: number
      field: string
      message: string
    }>
    warnings: Array<{
      line: number
      message: string
    }>
  }> {
    return this.handleRequest(
      () => this.http.upload('/api/permissions/validate-import', file),
      {
        showLoading: true,
        loadingMessage: '验证导入数据中...'
      }
    )
  }

  /**
   * 修复权限不一致问题
   */
  async repairPermissionInconsistencies(userId?: string): Promise<{
    fixedIssues: number
    remainingIssues: number
    details: Array<{
      issue: string
      status: 'fixed' | 'failed'
      message?: string
    }>
  }> {
    const url = userId ? `/api/permissions/repair/${userId}` : '/api/permissions/repair'
    return this.handleRequest(
      () => this.http.post(url),
      {
        showLoading: true,
        loadingMessage: '修复权限不一致问题中...',
        showSuccessMessage: true,
        successMessage: '权限修复完成'
      }
    )
  }

  /**
   * 获取权限依赖关系
   */
  async getPermissionDependencies(permissionName: string): Promise<{
    directDependencies: string[]
    indirectDependencies: string[]
    dependentPermissions: string[]
  }> {
    return this.handleRequest(
      () => this.http.get(`/api/permissions/dependencies/${permissionName}`),
      { showLoading: false }
    )
  }

  /**
   * 获取权限影响分析
   */
  async getPermissionImpactAnalysis(permissionName: string): Promise<{
    affectedUsers: Array<{
      userId: string
      userName: string
      roles: string[]
      organizations: Array<{
        id: string
        name: string
      }>
    }>
    affectedRoles: Array<{
      roleId: string
      roleName: string
      userCount: number
    }>
    estimatedImpact: 'low' | 'medium' | 'high' | 'critical'
  }> {
    return this.handleRequest(
      () => this.http.get(`/api/permissions/impact-analysis/${permissionName}`),
      { showLoading: false }
    )
  }
}

// 创建单例实例
export const permissionApi = new PermissionApiService()